package com.gwclh.personnel.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gwclh.personnel.bean.ResultVo;
import com.gwclh.personnel.common.annotation.OperLog;
import com.gwclh.personnel.common.constants.OperLogConstants;
import com.gwclh.personnel.domain.PageDomain;
import com.gwclh.personnel.entity.Employee;
import com.gwclh.personnel.entity.Internship;
import com.gwclh.personnel.entity.Station;
import com.gwclh.personnel.service.IEmployeeService;
import com.gwclh.personnel.service.IInternshipService;
import com.gwclh.personnel.service.IStationService;
import com.gwclh.personnel.shiro.AccountProfile;
import com.gwclh.personnel.utils.ShiroUtil;
import com.gwclh.personnel.vo.employeevo.BaseEmployeeVo;
import com.gwclh.personnel.vo.uservo.EntryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 *
 * @author gzhhh
 * @since 2020-07-24
 */
@RestController
@RequestMapping("/employees")
@Api(tags = "员工管理模块")
@Slf4j
public class EmployeeController extends BaseController {

    @Autowired
    IEmployeeService employeeService;

    @Autowired
    IInternshipService internshipService;

    @Autowired
    IStationService stationService;

    @PostMapping("")
    @ApiOperation(value = "添加员工")
    @OperLog(operModule = OperLogConstants.OPER_LOG_MODULE_EMP, operType = OperLogConstants.OPER_LOG_POST, operDesc = "添加员工")
    public ResultVo insertEmp(@Validated @RequestBody Employee employee,
                              @RequestParam(value = "internshipStartDate", required = false) String internshipStartDate,
                              @RequestParam(value = "internshipEndDate", required = false) String internshipEndDate) {
        int stationEmpCount = employeeService.count(new QueryWrapper<Employee>().eq("sta_id", employee.getStaId()));
        Station station = stationService.getById(employee.getStaId());
        Assert.isTrue(stationEmpCount < station.getStaCapacity(), "该岗位人数已满");

        Assert.isTrue(employeeService.save(employee), "员工入职失败");
        if (employee.getIsInternship()) {
            Internship internship = new Internship();
            internship.setEmpId(employee.getId());
            internship.setInternStatus(0);
            try {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(internshipStartDate);
                Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(internshipEndDate);
                internship.setStartDate(startDate);
                internship.setEndDate(endDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Assert.isTrue(internshipService.save(internship), "员工入职失败");
        }
        return ResultVo.success();
    }

    @GetMapping("")
    @ApiOperation(value = "分页查询员工列表")
    public ResultVo listEmploy(Employee employee, HttpServletRequest request) {
        // 根据请求获取分页信息
        PageDomain pageDomain = getPageParams(request);
        Map<String, Object> map = employeeService.pageEmployees(pageDomain, employee);
        return ResultVo.success(map);
    }

    @GetMapping("/list")
    @ApiOperation(value = "分页查询员工列表。部门管理用")
    public ResultVo listEmployToDept(Employee employee, HttpServletRequest request) {
        PageDomain pageDomain = getPageParams(request);
        return employeeService.listEmployeesToDept(pageDomain, employee);
    }


    @PutMapping("")
    @ApiOperation(value = "修改员工信息")
    public ResultVo updateEmployee(@Validated @RequestBody Employee employee,
                                   @RequestParam(value = "internshipStartDate", required = false) String
                                           internshipStartDate,
                                   @RequestParam(value = "internshipEndDate", required = false) String
                                           internshipEndDate) {
        Assert.isTrue(employeeService.updateById(employee), "更新员工信息失败");
        if (employee.getIsInternship()) {
            Internship internship = internshipService.getOne(new QueryWrapper<Internship>().eq("emp_id", employee.getId()));
            boolean isExist = true;
            if (internship == null) {
                isExist = false;
                internship = new Internship();
                internship.setEmpId(employee.getId());
                internship.setInternStatus(0);
            }
            try {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(internshipStartDate);
                Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(internshipEndDate);
                internship.setStartDate(startDate);
                internship.setEndDate(endDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (isExist)
                Assert.isTrue(internshipService.updateById(internship));
            else
                Assert.isTrue(internshipService.save(internship));
        }
        return ResultVo.success();
    }

    @GetMapping("/talent-pool")
    @ApiOperation(value = "查询人才库")
    public ResultVo pageTalentPool(Employee employee, HttpServletRequest request) {
        PageDomain pageDomain = getPageParams(request);
        Map<String, Object> map = employeeService.pageTalents(pageDomain, employee);
        return ResultVo.success(map);
    }

    @PatchMapping("/{id}")
    @ApiOperation(value = "入职")
    public ResultVo entryById(@PathVariable(value = "id") Integer empId,
                              @RequestBody @Validated EntryVo entryVo) {
        Employee employee = employeeService.getById(empId);
        employee.setDeptId(entryVo.getDeptId());
        employee.setStaId(entryVo.getStaId());
        employee.setEmpDate(entryVo.getEmpDate());
        employee.setWorkDate(entryVo.getWorkDate());
        employee.setEmpType(entryVo.getEmpType());
        employee.setIsInternship(entryVo.getIsInternship());
        employee.setIsTalents(false);
        boolean updateById = employeeService.updateById(employee);
        Assert.isTrue(updateById, "入职失败！");

        if (entryVo.getIsInternship()) {
            String[] internshipDate = entryVo.getInternshipDate();
            if (employee.getIsInternship()) {
                Internship internship = internshipService.getOne(new QueryWrapper<Internship>().eq(
                        "emp_id", employee.getId()));
                boolean isExist = true;
                if (internship == null) {
                    isExist = false;
                    internship = new Internship();
                    internship.setEmpId(employee.getId());
                    internship.setInternStatus(0);
                }
                try {
                    Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(internshipDate[0]);
                    Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(internshipDate[1]);
                    internship.setStartDate(startDate);
                    internship.setEndDate(endDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (isExist) Assert.isTrue(internshipService.updateById(internship), "入职失败！");
                else Assert.isTrue(internshipService.save(internship), "入职失败！");
            }
        }
        return ResultVo.success();
    }


    @GetMapping("/statistics/{pId}/entry")
    @ApiOperation(value = "根据公司统计部门月入职人数")
    public ResultVo statistics(@PathVariable(value = "pId") Integer pId) {
        return employeeService.statisticsEntryEmpByCompany(pId);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询员工信息")
    public ResultVo getById(@PathVariable(value = "id") Integer id) {
        Employee employee = employeeService.getById(id);
        Assert.notNull(employee, "查无此员工");
        return ResultVo.success(employee);
    }

    @PatchMapping("/talent/{id}")
    @ApiOperation(value = "根据id删除人才库员工")
    public ResultVo deleteTalentPoolById(@PathVariable(value = "id") Integer id) {
        boolean remove = employeeService.removeById(id);
        Assert.isTrue(remove, "删除失败！");
        return ResultVo.success();
    }

    @GetMapping("/internship/month/data")
    @ApiOperation(value = "查询每月转正人数")
    public ResultVo getInternshipDate() {
        List<Map<String, Object>> internshipMonthDate = employeeService.getInternshipMonthDate();
        return ResultVo.success(internshipMonthDate);
    }

    @GetMapping("/data/{pId}")
    public ResultVo getEntryDataByPid(@PathVariable(value = "pId") Integer pId) {
        List<Map<String, Object>> entryDataByPid = employeeService.getEntryDataByPid(pId);
        return ResultVo.success(entryDataByPid);
    }

    @GetMapping("/deptTranLog/{id}")
    public ResultVo getEmpToDeptLog(@PathVariable Integer id){

        return employeeService.getEmpTranLog(id);
    }
}
